// ProjectApproval.jsx 组件文件
import { Table, Button, Space, Modal, message, Tag, Card, Divider, Input, Avatar, Upload, Tabs } from '@/utils/antd-imports';
import { AuditOutlined, CheckOutlined, CloseOutlined, UserOutlined, SendOutlined, UploadOutlined } from '@/utils/icons';
import React, { useState } from 'react';








import Steps from 'antd/es/steps';




import { Comment } from '@ant-design/compatible';


const { TextArea } = Input;
const { TabPane } = Tabs;

const ProjectApproval = () => {
  const [approvalData, setApprovalData] = useState([
    {
      key: '1',
      projectName: '凯泽利新办公楼建设',
      applicant: '张三',
      applyDate: '2025-09-15',
      budget: '¥5,000,000',
      status: 'pending',
      description: '新办公楼建设项目，包含设计、施工和装修',
      projectCode: 'XM2025001',
      expenseType: '01-建设项目',
      expenseDetails: [
        { id: 1, type: '设计费用', amount: '¥500,000', description: '建筑设计及施工图纸' },
        { id: 2, type: '施工费用', amount: '¥4,000,000', description: '主体施工及材料' },
        { id: 3, type: '装修费用', amount: '¥500,000', description: '内部装修及配套设施' }
      ],
      paymentAccount: '张三 个人银行卡',
      approvalProcess: [
        { 
          title: '提交申请', 
          description: '张三', 
          date: '2025-09-15', 
          status: 'finish',
          comments: [
            {
              author: '张三',
              avatar: <Avatar icon={<UserOutlined />} />,
              content: <p>新办公楼建设项目申请提交，请审批。</p>,
              datetime: '2025-09-15 09:00',
              attachments: []
            }
          ]
        },
        { 
          title: '部门审批', 
          description: '李经理', 
          date: '2025-09-16', 
          status: 'finish',
          comments: [
            {
              author: '李经理',
              avatar: <Avatar icon={<UserOutlined />} />,
              content: <p>项目预算合理，符合公司发展规划，建议批准。</p>,
              datetime: '2025-09-16 10:30',
              attachments: [
                { name: '部门意见书.pdf', url: '#' }
              ]
            }
          ]
        },
        { 
          title: '财务审核', 
          description: '王会计', 
          date: '2025-09-17', 
          status: 'finish',
          comments: [
            {
              author: '王会计',
              avatar: <Avatar icon={<UserOutlined />} />,
              content: <p>财务数据核对无误，预算分配合理。</p>,
              datetime: '2025-09-17 14:20',
              attachments: [
                { name: '财务审核表.xlsx', url: '#' }
              ]
            }
          ]
        },
        { 
          title: '最终审批', 
          description: '等待朱泽名处理', 
          date: '', 
          status: 'process',
          comments: [],
          attachments: []
        }
      ]
    },
    {
      key: '2',
      projectName: 'ERP系统升级',
      applicant: '李四',
      applyDate: '2025-09-20',
      budget: '¥1,200,000',
      status: 'approved',
      description: '企业ERP系统升级至最新版本',
      projectCode: 'XM2025002',
      expenseType: '02-IT费用',
      expenseDetails: [
        { id: 1, type: '软件许可', amount: '¥800,000', description: '新版ERP系统授权' },
        { id: 2, type: '实施服务', amount: '¥300,000', description: '系统部署与配置' },
        { id: 3, type: '培训费用', amount: '¥100,000', description: '员工使用培训' }
      ],
      paymentAccount: '公司对公账户',
      approvalProcess: [
        { 
          title: '提交申请', 
          description: '李四', 
          date: '2025-09-20', 
          status: 'finish',
          comments: [
            {
              author: '李四',
              avatar: <Avatar icon={<UserOutlined />} />,
              content: <p>ERP系统升级申请提交，请审批。</p>,
              datetime: '2025-09-20 09:00',
              attachments: []
            }
          ]
        },
        { 
          title: '部门审批', 
          description: '张总监', 
          date: '2025-09-21', 
          status: 'finish',
          comments: [
            {
              author: '张总监',
              avatar: <Avatar icon={<UserOutlined />} />,
              content: <p>系统升级对提升工作效率很有帮助，建议尽快实施。</p>,
              datetime: '2025-09-21 09:15',
              attachments: [
                { name: '技术评估报告.pdf', url: '#' }
              ]
            }
          ]
        },
        { 
          title: '财务审核', 
          description: '王会计', 
          date: '2025-09-22', 
          status: 'finish',
          comments: [
            {
              author: '王会计',
              avatar: <Avatar icon={<UserOutlined />} />,
              content: <p>财务审核通过，预算合理。</p>,
              datetime: '2025-09-22 11:30',
              attachments: []
            }
          ]
        },
        { 
          title: '最终审批', 
          description: '朱泽名', 
          date: '2025-09-23', 
          status: 'finish',
          comments: [
            {
              author: '朱泽名',
              avatar: <Avatar icon={<UserOutlined />} />,
              content: <p>同意实施ERP系统升级项目。</p>,
              datetime: '2025-09-23 14:00',
              attachments: [
                { name: '审批意见书.pdf', url: '#' }
              ]
            }
          ]
        }
      ]
    }
  ]);

  const [selectedProject, setSelectedProject] = useState(null);
  const [commentText, setCommentText] = useState('');
  const [activeTab, setActiveTab] = useState('pending');
  const [fileList, setFileList] = useState([]);

  // 筛选不同状态的项目
  const pendingProjects = approvalData.filter(item => item.status === 'pending');
  const processedProjects = approvalData.filter(item => item.status !== 'pending');
  const myInitiatedProjects = approvalData.filter(item => item.applicant === '张三'); // 假设当前用户是张三

  const handleApprove = () => {
    if (!selectedProject) return;
    
    Modal.confirm({
      title: '确认审批通过',
      content: `确定要通过项目 "${selectedProject.projectName}" 的审批吗？`,
      onOk: () => {
        const newData = approvalData.map(item => 
          item.key === selectedProject.key ? { 
            ...item, 
            status: 'approved',
            approvalProcess: item.approvalProcess.map((step, index) => 
              index === item.approvalProcess.length - 1 ? 
              { 
                ...step, 
                description: '朱泽名', 
                date: new Date().toISOString().split('T')[0], 
                status: 'finish',
                comments: [
                  ...step.comments,
                  {
                    author: '朱泽名',
                    avatar: <Avatar icon={<UserOutlined />} />,
                    content: <p>项目审批通过，请按计划执行。</p>,
                    datetime: new Date().toLocaleString(),
                    attachments: fileList.map(file => ({
                      name: file.name,
                      url: '#'
                    }))
                  }
                ]
              } : step
            )
          } : item
        );
        setApprovalData(newData);
        setSelectedProject(newData.find(item => item.key === selectedProject.key));
        setFileList([]);
        setCommentText('');
        message.success('项目已审批通过');
      }
    });
  };

  const handleReject = () => {
    if (!selectedProject) return;
    
    Modal.confirm({
      title: '确认审批驳回',
      content: `确定要驳回项目 "${selectedProject.projectName}" 的审批吗？`,
      onOk: () => {
        const newData = approvalData.map(item => 
          item.key === selectedProject.key ? { 
            ...item, 
            status: 'rejected',
            approvalProcess: item.approvalProcess.map((step, index) => 
              index === item.approvalProcess.length - 1 ? 
              { 
                ...step, 
                description: '朱泽名', 
                date: new Date().toISOString().split('T')[0], 
                status: 'error',
                comments: [
                  ...step.comments,
                  {
                    author: '朱泽名',
                    avatar: <Avatar icon={<UserOutlined />} />,
                    content: <p>项目审批驳回，请根据反馈意见修改后重新提交。</p>,
                    datetime: new Date().toLocaleString(),
                    attachments: fileList.map(file => ({
                      name: file.name,
                      url: '#'
                    }))
                  }
                ]
              } : step
            )
          } : item
        );
        setApprovalData(newData);
        setSelectedProject(newData.find(item => item.key === selectedProject.key));
        setFileList([]);
        setCommentText('');
        message.warning('项目已驳回');
      }
    });
  };

  const showDetail = (record) => {
    setSelectedProject(record);
  };

  const handleCommentSubmit = () => {
    if (!selectedProject) return;
    
    if (!commentText.trim()) {
      message.warning('请输入评论内容');
      return;
    }

    const currentStepIndex = selectedProject.approvalProcess.findIndex(step => step.status === 'process');
    if (currentStepIndex === -1) return;

    const newData = approvalData.map(item => 
      item.key === selectedProject.key ? { 
        ...item, 
        approvalProcess: item.approvalProcess.map((step, index) => 
          index === currentStepIndex ? {
            ...step,
            comments: [
              ...step.comments,
              {
                author: '当前用户',
                avatar: <Avatar icon={<UserOutlined />} />,
                content: <p>{commentText}</p>,
                datetime: new Date().toLocaleString(),
                attachments: fileList.map(file => ({
                  name: file.name,
                  url: '#'
                }))
              }
            ]
          } : step
        )
      } : item
    );
    
    setApprovalData(newData);
    setSelectedProject(newData.find(item => item.key === selectedProject.key));
    setCommentText('');
    setFileList([]);
    message.success('评论已提交');
  };

  const columns = [
    {
      title: '项目名称',
      dataIndex: 'projectName',
      key: 'projectName',
      render: (text, record) => (
        <a onClick={() => showDetail(record)}>{text}</a>
      )
    },
    {
      title: '申请人',
      dataIndex: 'applicant',
      key: 'applicant'
    },
    {
      title: '申请日期',
      dataIndex: 'applyDate',
      key: 'applyDate'
    },
    {
      title: '预算金额',
      dataIndex: 'budget',
      key: 'budget'
    },
    {
      title: '审批状态',
      dataIndex: 'status',
      key: 'status',
      render: (status) => {
        let color = '';
        let text = '';
        switch (status) {
          case 'approved':
            color = 'green';
            text = '已通过';
            break;
          case 'rejected':
            color = 'red';
            text = '已驳回';
            break;
          default:
            color = 'orange';
            text = '待审批';
        }
        return <Tag color={color}>{text}</Tag>;
      }
    }
  ];

  // 根据当前激活的标签页选择显示的数据
  const getTableData = () => {
    switch (activeTab) {
      case 'pending':
        return pendingProjects;
      case 'processed':
        return processedProjects;
      case 'myInitiated':
        return myInitiatedProjects;
      default:
        return approvalData;
    }
  };

  const uploadProps = {
    onRemove: file => {
      const index = fileList.indexOf(file);
      const newFileList = fileList.slice();
      newFileList.splice(index, 1);
      setFileList(newFileList);
    },
    beforeUpload: file => {
      setFileList([...fileList, file]);
      return false;
    },
    fileList,
  };

  // 检查当前用户是否是当前审批环节的处理人
  const isCurrentApprover = (selectedProject) => {
    if (!selectedProject) return false;
    const currentStep = selectedProject.approvalProcess.find(step => step.status === 'process');
    return currentStep && currentStep.description.includes('朱泽名'); // 假设当前用户是朱泽名
  };

  return (
    <div style={{ backgroundColor: '#f5f5f5', minHeight: '100vh', padding: 16 }}>
      {/* 顶部卡片式Tab */}
      <Card style={{ marginBottom: 16 }}>
        <Tabs 
          type="card" 
          activeKey={activeTab} 
          onChange={setActiveTab}
        >
          <TabPane 
            tab={
              <span>
                <AuditOutlined />
                待处理的 ({pendingProjects.length})
              </span>
            } 
            key="pending"
          />
          <TabPane 
            tab={
              <span>
                <CheckOutlined />
                已处理的
              </span>
            } 
            key="processed"
          />
          <TabPane 
            tab={
              <span>
                <UserOutlined />
                我发起的
              </span>
            } 
            key="myInitiated"
          />
        </Tabs>

      <div style={{ display: 'flex', gap: 16 }}>
        {/* 左侧项目列表 */}
        <div style={{ width: 380, flexShrink: 0 }}>
          <Card 
            title="项目审批列表"
            bordered={false}
            style={{ boxShadow: '0 1px 3px rgba(0,0,0,0.1)', height: '100%' }}
          >
            <div style={{ overflowY: 'auto', height: 'calc(100vh - 220px)' }}>
              {getTableData().map(project => (
                <Card 
                  key={project.key}
                  style={{ 
                    marginBottom: 16, 
                    cursor: 'pointer',
                    borderLeft: selectedProject?.key === project.key ? '3px solid #1890ff' : '1px solid #f0f0f0'
                  }}
                  onClick={() => showDetail(project)}
                >
                  <div>
                    <h4 style={{ marginBottom: 8 }}>{project.projectName}</h4>
                    <Tag color={project.status === 'pending' ? 'orange' : project.status === 'approved' ? 'green' : 'red'}>
                      {project.status === 'pending' ? '待审批' : project.status === 'approved' ? '已通过' : '已驳回'}
                    </Tag>
                    <div style={{ color: '#666', fontSize: 12, marginTop: 8 }}>申请人: {project.applicant}</div>
                  </div>
                  <Divider style={{ margin: '12px 0' }} />
                  <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                    <div>
                      <div style={{ color: '#666', fontSize: 12 }}>预算金额</div>
                      <div>{project.budget}</div>
                    </div>
                    <div>
                      <div style={{ color: '#666', fontSize: 12 }}>申请日期</div>
                      <div>{project.applyDate}</div>
                    </div>
                  </div>
                </Card>
              ))}
            </div>
          </Card>
        </div>

        {/* 右侧审批内容 - 主要区域 */}
        <div style={{ flex: 1 }}>
          {selectedProject ? (
            <Card 
              title={`${selectedProject.applicant}提交的${selectedProject.projectName}`}
              bordered={false}
              style={{ boxShadow: '0 1px 3px rgba(0,0,0,0.1)', height: '100%' }}
              extra={
                <Space>
                  <Tag color={selectedProject.status === 'pending' ? 'orange' : selectedProject.status === 'approved' ? 'green' : 'red'}>
                    {selectedProject.status === 'pending' ? '等待朱泽名处理' : selectedProject.status === 'approved' ? '已通过' : '已驳回'}
                  </Tag>
                  {selectedProject.status === 'pending' && isCurrentApprover(selectedProject) && (
                    <Space>
                      <Button 
                        type="primary" 
                        icon={<CheckOutlined />} 
                        onClick={handleApprove}
                      >
                        通过
                      </Button>
                      <Button 
                        danger 
                        icon={<CloseOutlined />} 
                        onClick={handleReject}
                      >
                        驳回
                      </Button>
                    </Space>
                  )}
                </Space>
              }
            >
              <div style={{ display: 'flex', gap: 24, height: 'calc(100vh - 220px)', overflowY: 'auto' }}>
                {/* 左侧审批详情 */}
                <div style={{ flex: 1 }}>
                  <h3>项目详情</h3>
                  <div style={{ display: 'grid', gridTemplateColumns: '100px 1fr', gap: '12px 0', alignItems: 'center' }}>
                    <div style={{ fontWeight: 'bold', color: '#666' }}>申请人</div>
                    <div>{selectedProject.applicant}</div>
                    
                    <div style={{ fontWeight: 'bold', color: '#666' }}>项目名称</div>
                    <div>{selectedProject.projectName}</div>
                    
                    <div style={{ fontWeight: 'bold', color: '#666' }}>预算金额</div>
                    <div>{selectedProject.budget}</div>
                    
                    <div style={{ fontWeight: 'bold', color: '#666' }}>费用类型</div>
                    <div>{selectedProject.expenseType}</div>
                    
                    <div style={{ fontWeight: 'bold', color: '#666' }}>项目描述</div>
                    <div>{selectedProject.description}</div>
                  </div>
                  
                  <Divider />
                  
                  <h3>费用明细</h3>
                  <Table 
                    dataSource={selectedProject.expenseDetails} 
                    pagination={false}
                    size="small"
                    columns={[
                      { title: '序号', dataIndex: 'id', key: 'id', width: 60 },
                      { title: '费用类型', dataIndex: 'type', key: 'type' },
                      { title: '费用金额', dataIndex: 'amount', key: 'amount' },
                      { title: '费用说明', dataIndex: 'description', key: 'description' }
                    ]}
                  />
                  
                  <Divider />
                  
                  <h3>收款账户</h3>
                  <div>{selectedProject.paymentAccount}</div>
                </div>
                
                {/* 右侧审批流程 */}
                <div style={{ width: 500 }}>
                  <h3>审批流程</h3>
                  <Steps 
                    direction="vertical" 
                    size="small" 
                    current={selectedProject.approvalProcess.findIndex(step => step.status === 'process')}
                    items={selectedProject.approvalProcess.map(step => ({
                      title: step.title,
                      description: (
                        <div>
                          <div>{step.description}</div>
                          {step.date && <div style={{ color: '#999', fontSize: 12 }}>{step.date}</div>}
                        </div>
                      ),
                      status: step.status,
                      subTitle: step.comments.length > 0 && (
                        <div style={{ marginTop: 8 }}>
                          <div style={{ fontWeight: 'bold', marginBottom: 8 }}>审批意见:</div>
                          {step.comments.map((comment, idx) => (
                            <Comment
                              key={idx}
                              author={comment.author}
                              avatar={comment.avatar}
                              content={comment.content}
                              datetime={comment.datetime}
                              actions={comment.attachments?.length > 0 ? [
                                <Space>
                                  {comment.attachments.map((file, i) => (
                                    <a key={i} href={file.url} target="_blank" rel="noopener noreferrer">
                                      {file.name}
                                    </a>
                                  ))}
                                </Space>
                              ] : null}
                            />
                          ))}
                        </div>
                      )
                    }))}
                  />
                  
                  {/* 当前审批环节的评论输入框 */}
                  {selectedProject.status === 'pending' && isCurrentApprover(selectedProject) && (
                    <>
                      <Divider />
                      <h3>发表审批意见</h3>
                      <TextArea 
                        rows={4} 
                        placeholder="请输入审批意见..." 
                        value={commentText}
                        onChange={e => setCommentText(e.target.value)}
                        style={{ marginBottom: 16 }}
                      />
                      
                      <Upload {...uploadProps}>
                        <Button icon={<UploadOutlined />}>上传附件</Button>
                      </Upload>
                      
                      <div style={{ marginTop: 16, display: 'flex', justifyContent: 'flex-end' }}>
                        <Button 
                          type="primary" 
                          icon={<SendOutlined />} 
                          onClick={handleCommentSubmit}
                        >
                          提交意见
                        </Button>
                      </div>
                    </>
                  )}
                </div>
              </div>
            </Card>
          ) : (
            <Card 
              bordered={false}
              style={{ 
                boxShadow: '0 1px 3px rgba(0,0,0,0.1)', 
                height: '100%',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center'
              }}
            >
              <div style={{ textAlign: 'center', color: '#999' }}>
                <AuditOutlined style={{ fontSize: 48, marginBottom: 16 }} />
                <div>请从左侧列表选择一个审批项目</div>
              </div>
            </Card>
          )}
        </div>
      </div>
      </Card>
    </div>
  );
};

export default ProjectApproval;